package com.changgou.pay.service.impl;

import com.changgou.pay.service.WXPayService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zero
 * @date 2020/7/13
 */

@Service
public class WXPayServiceImpl implements WXPayService {

    @Autowired
    private WXPay wxPay;

    @Value("${wxpay.notify_url}")
    private String notify_url;

    @Override
    public Map nativePay(String orderId, Integer money) {
        try {
            //封装请求参数
            Map<String,String> map = new HashMap<>();

            map.put("body","畅购商城商品");
            map.put("out_trade_no",orderId);
            //封装价格,微信的默认单位是分,需要进行处理
            BigDecimal payMoney = new BigDecimal("0.01");   //0.01元
            BigDecimal fen = payMoney.multiply(new BigDecimal(100));  //1.00分
            fen = fen.setScale(0, BigDecimal.ROUND_UP);     //1分
            map.put("total_fee",String.valueOf(fen));
            map.put("spbill_create_ip","127.0.0.1");
            map.put("notify_url",notify_url);
            map.put("trade_type","NATIVE");

            //调用统一下单的接口
            Map<String, String> resultMap = wxPay.unifiedOrder(map);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 基于微信端查询订单的状态
     * @param orderId
     * @return
     */
    @Override
    public Map queryOrder(String orderId) {

        HashMap<String, String> param = new HashMap<>();
        param.put("out_trade_no",orderId);
        try {
            Map<String, String> resultMap = wxPay.orderQuery(param);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 基于微信 根据订单id关闭订单
     * @param orderId
     * @return
     */
    @Override
    public Map closeOrder(String orderId) {

        Map<String,String> map = new HashMap<>();
        map.put("orderId",orderId);

        try {
            Map<String, String> resultMap = wxPay.closeOrder(map);

            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
